<?php

namespace Yolo\Commands;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Support\Filesystem\Filesystem;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputOption;
use Yolo\Di\DI;
use Yolo\Packages\PackageManager;
use Yolo\Service\ApplicationContainer;

#[Command]
class RemovePackage extends HyperfCommand
{
    private ApplicationContainer $applicationContainer;

    private PackageManager $packageManager;

    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('package:remove');

        $this->applicationContainer = DI::use(ApplicationContainer::class);
        $this->packageManager = DI::use(PackageManager::class);
    }

    public function configure(): void
    {
        parent::configure();
        $this->setDescription('Remove a package.');
        $this->addArgument('package', InputOption::VALUE_REQUIRED, 'Package name.');
    }

    public function handle(): void
    {
        $package = $this->input->getArgument('package');

        $this->info("Removing package: $package");

        $packageLock = $this->packageManager->getPackageLockDependency($package);

        if ($packageLock) {
            $filesystem = new Filesystem();
            $filesystem->deleteDirectory($packageLock['path']);
        }

        $this->packageManager->removeDependency($package);
        $this->packageManager->removePackageLockDependency($package);

        $this->packageManager->savePackageFile();
        $this->packageManager->savePackageLockFile();

        $this->info("Package removed successfully.");
    }
}
